package com.qianxunclub.chapter15;


import java.util.ArrayList;
import java.util.List;

/**
 * @author zhangbin
 */
public class Application {

    public static List<Long> list = new ArrayList<>();

    public static void main(String[] args) throws Exception {
        Thread thread = new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getId());
            }
        });
        thread.start();

        list.add(thread.getId());

        Thread thread2 = new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getId());
            }
        });
        thread2.start();

        list.add(thread2.getId());

        Thread.sleep(5000);
        Thread my = Application.findThread(list.get(0));
        my.stop();

    }

    public static Thread findThread(long threadId) {
        ThreadGroup group = Thread.currentThread().getThreadGroup();
        while (group != null) {
            Thread[] threads = new Thread[(int) (group.activeCount() * 1.2)];
            int count = group.enumerate(threads, true);
            for (int i = 0; i < count; i++) {
                if (threadId == threads[i].getId()) {
                    return threads[i];
                }
            }
            group = group.getParent();
        }
        return null;
    }

}
